// pages/product/productDetail/index.js
const app = getApp()
const service = require('../../../service/port.js')
const serviceActivity = require('../../../service/activity')
const evaluateService = require("../../../service/evaluate")
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isServiceTipHidden: true, //控制服务隐藏的标记值
    swiperList: [],
    commentList:[],
    productDetailImg: [],
    time: 30 * 60 * 60 * 1000,
    endTime: "",
    timeData: {},
    show: false,
    detail: {
      price: 10,
      monthSale: 1000,
      diamond: 3,
      name: "碧耐丝草本植萃护发泡泡染"
    },
    spudetail: {},
    servicetext: '',
    expressText: "",
    specification: [{
      title: "规格分类",
      tag: []
    }],
    currentsku: '',
    currentInfo: {},
    currentnum: 1,
    isnewOpen: true,
    spuId: '',
    serviceList: [],
    showLogin: false,
    disabled: false,
    countDownText: "距结束仅剩",
    status: "",
    promotiomIds: "",
    disabled1: false,
    nomoredata:false,
    commentNum:0,
    videoUrl:[]
  },
  onChangetime(e) {
    let timeData = e.detail
    let hours = timeData.hours < 10 ? '0' + timeData.hours :  timeData.hours
    let minutes = timeData.minutes < 10 ? '0' + timeData.minutes :  timeData.minutes
    let seconds = timeData.seconds < 10 ? '0' + timeData.seconds :  timeData.seconds
    timeData = {hours , minutes ,seconds}
    this.setData({
      timeData: timeData,
    });
    if (e.detail.hours == 0 && e.detail.minutes == 0 && e.detail.seconds == 0) {
      this.setData({
        disabled: this.data.status == false ? false : true,
      })
    }
  },
  showServiceTip() {
    this.setData({
      isServiceTipHidden: false
    })
  },
  hideServiceTip() {
    this.setData({
      isServiceTipHidden: true
    })
  },
  changeSwiper(e){
    //console.log(e)
    if(e.detail.current==0){
      this.videoContext.play()
    }else{
      this.videoContext.stop()
    }
   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    const id = options.id;
    this.setData({
      
      endTime: options.endTime,
      countDownText: options.status == "false" ? "距开始仅剩" : "距结束仅剩",
      status: options.status,
      disabled: options.status == "false" ? true : false,
    })
    wx.showLoading({
      title: '加载中...',
    })
    serviceActivity.getgoodDetail(id, res => {
      console.log(res);
      if (res.code != '00000') {
        wx.showToast({
          title: '商品已下架！',
          icon: 'none',
          duration: 3000,
          mask: true,
          success() {
            wx.navigateBack({
              delta: 1
            })
          }
        })
        return
      }
      var list = [];
      var imgList = []
      if (res.data.spuDetailes.images) {
        var imgJson = JSON.parse(res.data.spuDetailes.images);
        list = imgJson.temBanner.split(",");
        imgList = imgJson.itemDetail.split(",");
      }

      //res.data.tbSpu.image = list[0];
      var expressText = ((res.data.spuDetailes.freeNum == 0 || res.data.spuDetailes.freeNum == null) ? '' : "满" + res.data.spuDetailes.freeNum + "件包邮 ") + ((res.data.spuDetailes.freeMoney == 0 || res.data.spuDetailes.freeMoney == null) ? '' : " 满" + res.data.spuDetailes.freeMoney / 100 + "元包邮")
      var servicetext = ""
      for (let i = 0; i < res.data.serviceList.length; i++) {
        const element = res.data.serviceList[i];
        servicetext += element.serviceName + '  ';
      }
      
     
      this.setData({
        spudetail: res.data.spuDetailes,
        detail: res.data.tbSpu,
        swiperList: list,
        productDetailImg: imgList,
        currentInfo: res.data.skuDetailes[0],
        expressText: expressText,
        servicetext: servicetext,
        serviceList: res.data.serviceList,
        time: new Date(this.data.endTime.replace(/-/g, '/')).getTime() - new Date(res.data.Time.replace(/-/g, '/')).getTime(),
        specification: [{
          title: "规格分类",
          tag: res.data.skuDetailes
        }],
        promotiomIds: res.data.skuDetailes[0].seckillId,
        spuId: res.data.spuDetailes.spuId,
        videoUrl:res.data.spuDetailes.video
      })
      evaluateService.getAllevaluate({
        "data": {
          //用户id
          "spuId": res.data.spuDetailes.spuId
        },
        //分页
        "queryRequest": {
          //页码
          "pageNum": 1,
          //面数据量
          "pageSize": 3
        }
  
      }, res => {
        console.log(res)
  
        this.setData({
          commentNum: res.data.total
        })
        if (res.data.rows.length == 0) {
          this.setData({
            nomoredata: true
          })
        } else {
          for (let i = 0; i < res.data.rows.length; i++) {
            const element = res.data.rows[i];
            element.overall = ((element.score * 0.7 * 100 + element.pdScore * 0.3 * 100) / 100).toFixed(1)
          }
          this.setData({
            commentList: res.data.rows
          })
        }
  
      })


    })
    
  },
  previewImg: function (e) {
    console.log(e);
    var item = e.currentTarget.dataset.item;
    var imgUrls = e.currentTarget.dataset.item;
    //图片预览
    wx.previewImage({
      current: imgUrls, // 当前显示图片的http链接
      urls: this.data.swiperList
    })
  },
  previewImg1(e){
    //console.log(e);
    var list=[];
    e.currentTarget.dataset.imglist.forEach(element => {
      list.push(element.picUrl)
    });
    var imgUrls = e.currentTarget.dataset.item;
    //图片预览
    wx.previewImage({
      current: imgUrls, // 当前显示图片的http链接
      urls: list
    })
  },
  goAll() {
    wx.navigateTo({
      url: '/pages/product/allEvaluate/index?spuId=' + this.data.spuId,
    })
  },
  onClose: function () {
    this.setData({
      show: false
    })
  },
  onClose1: function () {
    this.setData({
      showLogin: false
    })
  },
  showpop: function () {
    if (app.globalData.userInfo == null) {
      // this.setData({
      //   isnewOpen: false
      // })
      // wx.navigateTo({
      //   url: '/pages/remindlogin/index',
      // })
      this.setData({
        showLogin: true
      })
    } else {
      this.setData({
        show: true
      })


    }
  },
  choose: function (e) {
    //console.log(e)
    // var index = e.currentTarget.dataset.index;
    // var array = e.currentTarget.dataset.array;

    // array.forEach(item=>{
    //   item.active=false
    // })
    // array[index].active=true;
    console.log('item',e.currentTarget.dataset.item)
    this.setData({
      disabled1 : false,
      currentsku: e.currentTarget.dataset.item.id,
      currentInfo: e.currentTarget.dataset.item
    })

     if (this.data.currentInfo.seckillStockNow == 0) {
        this.setData({
          disabled1: true
        })
      }
  },
  handleContact(e) {
    console.log(e.detail.path)
    console.log(e.detail.query)
  },
  //添加购物车
  addcart() {
    if (this.data.currentsku == '') {
      Toast.fail('请选择规格');
      return
    }
    if (this.data.currentInfo.stock == 0) {
      Toast.fail('该商品规格无库存！');
      return
    }
    service.addcart({
      customerId: wx.getStorageSync('userInfo').id,
      spuId: this.data.spuId,
      skuId: this.data.currentsku,
      num: this.data.currentnum
    }, res => {
      Toast.success('已加入购物车');
      this.setData({
        show: false
      })
    })
  },
  onChange(event) {
    console.log(event.detail);
    this.setData({
      currentnum: event.detail
    })
  },
  loginsucc() {
    this.setData({
      showLogin: false
    })
    if (wx.getStorageSync('userInfo').mobile == null || wx.getStorageSync('userInfo').mobile == "") {
      wx.navigateTo({
        url: 'pages/phone/index',
      })
    }
  },
  buyNow() {
    if (this.data.currentsku == '') {
      Toast.fail('请选择规格');
      return
    }
    if (this.data.currentInfo.stock == 0) {
      Toast.fail('该商品规格无库存！');
      return
    }

    // wx.setStorageSync("activitygood", this.data);
    // wx.setStorageSync("type", "miaosha");
    // this.setData({
    //   show: false
    // })
    // wx.navigateTo({
    //   url: '/pages/activity/confirmOrder/index',
    // })
    this.toFinalConfirmOrder()
  },

  toFinalConfirmOrder () {
  
    let totalMoney = this.data.currentInfo.killMoney
    let currentInfo = {
      ...this.data.currentInfo,
      num : this.data.currentnum ,//购买数量
      skuId: this.data.currentsku,
    }
    let orderInfo = {
      type: '1',
      promotiomIds : this.data.promotiomIds,
      shoppingList: [currentInfo],
      totalMoney: totalMoney,
    }
    
    console.log('orderInfo===========')
    console.log('秒杀哦',orderInfo)
    console.log('orderInfo===========')
    orderInfo = JSON.stringify(orderInfo)
    wx.navigateTo({
      url: `/pages/order/finalComfirmOrder/index?orderInfo=${orderInfo}`,
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!this.data.isnewOpen) {
      this.setData({
        show: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})